<template>
  <div class="post-detail">
    <el-card class="post-card">
      <template #header>
        <div class="post-header">
          <h1>{{ post.title }}</h1>
          <div class="post-meta">
            <el-tag :type="getStatusTagType(post.status)">
              {{ post.status_display }}
            </el-tag>
            <span class="post-date">{{ formatDateTime(post.created_at) }}</span>
            <span class="post-author">作者: {{ post.user_nickname }}</span>
          </div>
        </div>
      </template>
      
      <div class="post-content" v-html="post.content"></div>
      
      <div class="post-footer">
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
    
    <!-- 评论区域 -->
    <CommentList 
      ref="commentListRef"
      :module-id="'post'" 
      :fid="postId" 
      :show-input="true"
      @comment-submitted="handleCommentSubmitted"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import CommentList from '@/components/CommentList.vue'
import { formatDateTime } from '@/utils'

const route = useRoute()
const router = useRouter()

const post = ref<any>({})
const commentListRef = ref<any>(null)
const postId = ref<number>(0)

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'published':
      return 'success'
    case 'draft':
      return 'info'
    case 'hidden':
      return 'warning'
    default:
      return 'info'
  }
}



// 获取帖子详情
const fetchPostDetail = async (id: string) => {
  try {
    const response: any = await request.get(`/health/posts/${id}/`)
    post.value = response
    postId.value = response.id
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
    router.push('/app/health/posts')
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 处理评论提交事件
const handleCommentSubmitted = () => {
  // 评论提交成功后可以做一些处理，比如刷新评论列表
  if (commentListRef.value) {
    commentListRef.value.refreshComments()
  }
}

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchPostDetail(newId as string)
  }
}, { immediate: true })

onMounted(() => {
  const postIdParam = route.params.id as string
  if (postIdParam) {
    fetchPostDetail(postIdParam)
  } else {
    ElMessage.error('帖子ID无效')
    router.push('/app/health/posts')
  }
})
</script>

<style scoped>
.post-detail {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.post-header h1 {
  margin: 0 0 10px 0;
  color: #333;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.post-date, .post-author {
  color: #666;
  font-size: 14px;
}

.post-content {
  padding: 20px 0;
  line-height: 1.8;
}

.post-content :deep(img) {
  max-width: 100%;
  height: auto;
}

.post-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
</style>